<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title>账号管理 - 8282管理系统</title>
    <link rel="icon" href="favicon.ico" type="image/ico">
    <meta name="keywords" content="8282管理系统,egg.js,Bootstrap,JQ,node.js,后台模板,后台管理系统">
    <meta name="description" content="8282管理系统是基于Egg.js+LightYear构建的后台管理系统。">
    <meta name="author" content="cadcamzy">
    <link href="/public/css/bootstrap.min.css" rel="stylesheet">
    <link href="/public/css/materialdesignicons.min.css" rel="stylesheet">
    <link href="/public/js/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
    <link href="/public/css/animate.css" rel="stylesheet">
    <link href="/public/css/style.min.css" rel="stylesheet">
    <link href="/public/css/select2.min.css" rel="stylesheet">
    <link href="/public/css/validation.css" rel="stylesheet">
    <style>
        .select2-container {
            width: 100%!important; /* 作用于select2 控件 */
        }
    </style>
</head>

<body>
    <div class="container-fluid p-t-15">

        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h4>账号管理</h4>
                    </div>
                    <div class="card-body">
                        <div id="toolbar" class="toolbar-btn-action">
                            <button id="btn_add" type="button" class="btn btn-primary m-r-5">
                                <span class="mdi mdi-plus" aria-hidden="true"></span>新增
                            </button>
                            <button id="btn_edit" type="button" class="btn btn-success m-r-5">
                                <span class="mdi mdi-check" aria-hidden="true"></span>修改
                            </button>
                            <button id="btn_delete" type="button" class="btn btn-danger m-r-5">
                                <span class="mdi mdi-window-close" aria-hidden="true"></span>删除
                            </button>
                            <button id="btn_search" type="button" class="btn btn btn-purple m-r-5">
                                <span class="mdi mdi-search-web" aria-hidden="true"></span>搜索
                            </button>
                            <button id="btn_refresh" type="button" class="btn btn-secondary m-r-5" onclick="javascript:location.reload();">
                                <span class="mdi mdi-refresh" aria-hidden="true"></span>刷新
                            </button>
                        </div>
                        <table id="db_table"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="search_modal" class="modal fade" tabindex="-2" role="dialog" aria-labelledby="myLargeModalLabel"
        data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myLargeModalLabel2">条件搜索</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group" id="search_tags">
                        <span class="label label-outline-purple">搜索条件</span>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="search_field">字段:</label>
                        <select class="form-control" id="search_field" size="1"></select>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="search_text">搜索内容:</label>
                        <input class="form-control" type="text" id="search_text" placeholder="请输入搜索内容..">
                        <button id="btn_search_reset" type="button" class="btn btn-danger m-t-10 m-r-5">重置条件</button>
                        <button id="btn_search_add" type="button" class="btn btn-primary m-t-10 m-r-5">添加条件</button>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button id="btn_search_submit" type="button" class="btn btn-purple">搜索</button>
                </div>
            </div>
        </div>
    </div>
    <div id="new_modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"
        data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myLargeModalLabel">新增账号</h4>
                </div>
                <div class="modal-body"><form id="new_modal_form">
                    <div class="form-group">
                        <label class="control-label" for="account">账号:</label>
                        <input class="form-control" type="text" id="account" name="account" placeholder="请输入账号..">
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="password">密码:</label>
                        <input class="form-control" type="text" id="password" name="password" placeholder="请输入密码..">
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="role_id">角色:</label>
                        <select class="form-control js_select2" id="role_id" name="role_id" size="1">
                            <option value="">请选择</option>
                            {% for role in roles %}
                            <option value="{{ role.id }}">{{ role.title }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="name">姓名:</label>
                        <input class="form-control" type="text" id="name" name="name" placeholder="请输入姓名..">
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="email">Email:</label>
                        <input class="form-control" type="email" id="email" name="email" placeholder="请输入邮箱..">
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="status">状态:</label>
                        <select class="form-control" id="status" name="status" size="1">
                            <option value="1">启用</option>
                            <option value="0">禁用</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button id="btn_save" type="button" class="btn btn-primary">点击保存</button>
                </div></form>
            </div>
        </div>
    </div>

    <script type="text/javascript" src="/public/js/jquery.min.js"></script>
    <script type="text/javascript" src="/public/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="/public/js/perfect-scrollbar.min.js"></script>
    <script type="text/javascript" src="/public/js/bootstrap-table/bootstrap-table.min.js"></script>
    <script type="text/javascript" src="/public/js/bootstrap-table/bootstrap-table-zh-CN.min.js"></script>

    <script type="text/javascript" src="/public/js/jquery.validate/jquery.validate.min.js"></script>
    <script type="text/javascript" src="/public/js/jquery.validate/messages_zh.min.js"></script>

    <script type="text/javascript" src="/public/js/select2/select2.min.js"></script>
    <script type="text/javascript" src="/public/js/select2/zh-CN.js"></script>

    <!--行内编辑插件-->
    <link href="/public/js/x-editable/1.5.1/bootstrap3-editable/css/bootstrap-editable.min.css" rel="stylesheet">
    <script type="text/javascript"
        src="/public/js/x-editable/1.5.1/bootstrap3-editable/js/bootstrap-editable.min.js"></script>
    <script type="text/javascript"
        src="/public/js/bootstrap-table/extensions/editable/bootstrap-table-editable.min.js"></script>

    <script type="text/javascript" src="/public/js/main.min.js"></script>
    <script type="text/javascript">
        let validate = JSON.parse( '{{validate | safe}}' ); // safe管道命令是不转义 validate中字符
        let myValidate;

        $().ready( function() {
            myValidate = $("#new_modal_form").validate(validate);

            $("#role_id").select2(); //可搜索下拉框初始化
            $.fn.modal.Constructor.prototype.enforceFocus = function () { }; //重写模态框的焦点函数，解决select2下拉不能输入的问题。
        });

        const columns = [
            { checkbox: true },    // 是否显示复选框
            { field: 'id', title: 'ID', sortable: true },    // 是否排序
            { field: 'account', title: '账号' },
            { field: 'role.roleName', title: '角色组' },
            //    { field: 'password', title: '密码' },
            { field: 'name', title: '名称' },
            { field: 'email', title: 'Email' },
            { field: 'status', title: '状态', editable: {
                    type: 'select',
                    title: "状态",
                    pk: 1,
                    source: [
                        { value: 0, text: '禁用' },
                        { value: 1, text: '正常' }
                    ],
                    noeditFormatter: function (value, row, index) {
                        var result;

                        if (value == '0' || value == '禁用') {
                            result = { filed: "status", value: "禁用", class: "label label-danger" };
                        } else if (value == '1' || value == '正常') {
                            result = { filed: "status", value: "正常", class: "label label-success" };
                        }

                        return result; // 这里对bootstrap-table-editable.min.js做了一些修改，让其能接收class
                    },
                    // 可以按列分开做保存，也可以用后面的onEditableSave
                    url: "/system/accounts/0",
                    ajaxOptions: {
                        type: 'put',
                        dataType: 'json'
                    }, // 默认是post方式提交,这里因为跨域,改成get
                    success: function (response, newValue) {
                        if (response.code == '200') {
                            // 这里的状态显示有自定义样式区分，做单元格更新
                            $('#tb_departments').bootstrapTable('updateCellById', { id: response.id, field: 'status', value: newValue });
                        } else {
                            return response.msg;
                        }
                    },
                    highlight: false
                }
            },
            { field: 'operate', title: '操作', formatter: btnGroup,  // 自定义方法
                events: {
                    'click .edit-btn': function (event, value, row, index) {
                        editUser(row.id);
                    },
                    'click .del-btn': function (event, value, row, index) {
                        delUser(row.id);
                    }
                }
            }
        ]
        const db_table = $('#db_table');
        const search_modal = $("#search_modal");
        const new_modal = $("#new_modal");

        let fieldName = {};
        $("#btn_search").click(function (){
            let options = [];
            new_modal.find('[name]').each(function() {
                const _this = $(this);
                const label = _this.prev().text().replace(':','').split('(')[0];
                const field = _this.attr('name');
                options.push(`<option value="${field}">${label}</option>`);
                fieldName[field] = label;
            });
            $("#search_field").html(options.join(''));
            search_modal.modal('show');
        });

        let searchParams = {};
        $("#btn_search_add").click(function() {
            // 添加搜索条件
            const field = $("#search_field").val();
            const text = $("#search_text").val();
            const search_tags = $("#search_tags");
            searchParams[field] = text;
            search_tags.html('');
            for(let key in searchParams) {
                const template = `<span class="label label-outline-${randomColor()} mr-r-4">${fieldName[key]}:${searchParams[key]}</span>`;
                search_tags.append(template);
            }
        });

        $("#btn_search_reset").click(function() {
            searchParams = {};
            $("#search_tags").html('<span class="label label-outline-purple">搜索条件</span>');
        })

        // 构建Bootstraptable 的查询参数
        let queryParams = function(params) {
            let temp = {
                limit: params.limit,         // 每页数据量
                offset: params.offset,       // sql语句起始索引
                page: (params.offset / params.limit) + 1,
                sort: params.sort,           // 排序的列名
                sortOrder: params.order      // 排序方式'asc' 'desc'
            };
            return $.extend({}, temp, searchParams);
        };

        $("#btn_search_submit").click(function() {
            // 提交搜索
            if ('{}' === JSON.stringify(searchParams)) {
                parent.lightyear.notify('搜索条件为空，请先添加！', 'warning', 3500, 'mdi mdi-emoticon-devil', 'top', 'center');
            }else {
                db_table.bootstrapTable('refresh');
                search_modal.modal('hide');
            }
        });

        let edit_status = 'new';
        let editUser = function(id) {
            edit_status = 'edit';

            $("#myLargeModalLabel").html('编辑账号');
            $.ajax({
                type: "get",
                url: "/system/accounts/" + id,
                data: "",
                dataType: 'json',
                success: function (data, status) {
                    if (data.code == '200') {
                        // 这里的状态显示有自定义样式区分，做单行的更新
                        const json = data.data;
                        new_modal.find('[name]').each(function() {
                            const _this = $(this);
                            const field = _this.attr('name');
                            if(field==='status') _this.val(json[field] ? "1" : "0");
                            else if(field==='role_id') _this.select2("val", String(json[field]).split(',')); // select2 需要赋值为数组，以兼容多选
                            else _this.val(json[field]);
                        });
                        new_modal.modal('show');
                    } else {
                        parent.lightyear.notify(data.msg, 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                    }
                },
                error: function () {
                    parent.lightyear.notify('获取指定数据失败, 请稍后尝试！', 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                }
            });
        };

        let delUser = function(id) {
            parent.$.confirm({
                title: '删除确认', type: 'red', typeAnimated: true,
                content: `你是否确认删除编号：[${id}] 的账号？`,
                buttons: {
                    confirm: {
                        text: '确认',
                        action: function(){
                            $.ajax({
                                type: "delete",
                                url: "/system/accounts/" + id,
                                data: "",
                                dataType: 'json',
                                success: function (data, status) {
                                    if (data.code == '200') {
                                        parent.lightyear.notify(data.msg, 'success', 3500, 'mdi mdi-emoticon-happy', 'top', 'center');
                                        db_table.bootstrapTable('refresh');
                                        new_modal.modal('hide');
                                    } else {
                                        parent.lightyear.notify(data.msg, 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                                    }
                                },
                                error: function () {
                                    parent.lightyear.notify('发生错误，请稍后尝试！', 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                                }
                            });
                        }
                    },
                    cancel: { text: '取消', },
                }
            });
        };

        let saveUser = function() {
            let data = {};
            new_modal.find('[name]').each(function() {
                const _this = $(this);
                const field = _this.attr('name');
                if(field === 'status') data[field] = _this.val() === "1" ? true : false;
                data[field] = _this.val();
            });

            if(edit_status === 'new') {
                // 新增
                if(!data.password || data.password.length < 6 || data.password.length > 30 ) {
                    parent.lightyear.notify('密码字段需为长度6~30位', 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                    return;
                }
                $.ajax({
                    type: "post",
                    url: "/system/accounts",
                    data: data,
                    dataType: 'json',
                    success: function (data, status) {
                        if (data.code === 201) {
                            parent.lightyear.notify(data.msg, 'success', 3500, 'mdi mdi-emoticon-happly', 'top', 'center');
                            db_table.bootstrapTable('refresh');
                        }
                        new_modal.modal('hide');
                    },
                    error: function (e) {
                        parent.lightyear.notify('修改失败，请稍后再试', 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                    }
                });
            } else if(edit_status === 'edit') {
                //编辑
                const rows = db_table.bootstrapTable('getSelections');
                const id = rows[0].id;
                $.ajax({
                    type: "put",
                    url: "/system/accounts/" + id,
                    data: data,
                    dataType: 'json',
                    success: function (data, status) {
                        if (data.code == '200') {
                            // 这里的状态显示有自定义样式区分，做单行的更新
                            parent.lightyear.notify(data.msg, 'success', 3500, 'mdi mdi-emoticon-happly', 'top', 'center');
                            db_table.bootstrapTable('refresh');
                            new_modal.modal('hide');
                        } else {
                            parent.lightyear.notify(data.msg, 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                        }
                    },
                    error: function () {
                        parent.lightyear.notify('修改失败，请稍后再试', 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                    }
                });
            }
        };

        db_table.bootstrapTable({
            classes: 'table table-bordered table-hover table-striped',
            url: '/system/accounts',
            method: 'get',
            dataType: 'json',        // 因为本示例中是跨域的调用,所以涉及到ajax都采用jsonp,
            uniqueId: 'id',
            idField: 'id',             // 每行的唯一标识字段
            toolbar: '#toolbar',       // 工具按钮容器
            clickToSelect: true,     // 是否启用点击选中行
            showColumns: true,         // 是否显示所有的列
            showRefresh: true,         // 是否显示刷新按钮
            singleSelect: true,         // 禁止多选
            //showToggle: true,        // 是否显示详细视图和列表视图的切换按钮(clickToSelect同时设置为true时点击会报错)

            pagination: true,                    // 是否显示分页
            sortOrder: "desc",                    // 排序方式
            queryParams: queryParams,     // 传递参数
            sidePagination: "server",            // 分页方式：client客户端分页，server服务端分页
            pageNumber: 1,                       // 初始化加载第一页，默认第一页
            pageSize: 10,                        // 每页的记录行数
            pageList: [10, 25, 50, 100],         // 可供选择的每页的行数
            search: false,                      // 是否显示表格搜索，此搜索是客户端搜索

            //showExport: true,        // 是否显示导出按钮, 导出功能需要导出插件支持(tableexport.min.js)
            //exportDataType: "basic", // 导出数据类型, 'basic':当前页, 'all':所有数据, 'selected':选中的数据

            columns: columns,
            onLoadSuccess: function (data) {
                $("[data-toggle='tooltip']").tooltip();
            }
        });

        // 操作按钮
        function btnGroup() {
            let html =
                '<a href="#!" class="btn btn-xs btn-default m-r-5 edit-btn" title="编辑" data-toggle="tooltip"><i class="mdi mdi-pencil"></i></a>' +
                '<a href="#!" class="btn btn-xs btn-default del-btn" title="删除" data-toggle="tooltip"><i class="mdi mdi-window-close"></i></a>';
            return html;
        }

        new_modal.on('hide.bs.modal', function () {
            // 关闭模态框时取消选中行
            db_table.bootstrapTable('uncheckAll');
            myValidate.resetForm(); //重置表单校验
        });

        // 新增
        $("#btn_add").click(function () {
            edit_status = 'new';

            $("#myLargeModalLabel").html('新增账号');
            new_modal.find('[name]').each(function() {
                const _this = $(this);
                _this.val('');
            });
            $("#role_id").select2('val', ['']);
            new_modal.modal('show');
        });
        // 编辑
        $("#btn_edit").click(function () {
            edit_status = 'edit';

            //得到表格选中行的id
            const rows = db_table.bootstrapTable('getSelections');
            if (!rows[0] || !rows[0].id) {
                parent.lightyear.notify('请先选择一条记录！', 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                return;
            }
            const id = rows[0].id;
            if(!id) {
                parent.lightyear.notify('选中的数据不正确！', 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
            }else {
                editUser(id);
            }
        });
        
        $("#btn_save").click( function() {
            //验证通过后，调用保存
            if (myValidate.form()) saveUser();
        });

        $("#btn_delete").click( function() {
            const rows = db_table.bootstrapTable('getSelections');
            if (!rows[0] || !rows[0].id) {
                parent.lightyear.notify('请先选择一条记录！', 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                return;
            }
            delUser(rows[0].id);
        });
    </script>
</body>

</html>